#coding=utf-8
import json
import time

import pandas as pd
import requests
from common.readExcel import *

class CreateUser:
    def __init__(self,token,host,worksiteId):
        self.token =token
        self.header = {
            'Content-Type': 'application/json;charset=UTF-8',
            'Authorization': 'Bearer ' + self.token
        }
        self.host = host
        self.worksiteId = worksiteId
    '''
    获取为身份证号
    '''
    def reqIdCard(self):
        payload = {}
        url = self.host+"/api/peopleManage/member/generateMemberId"  # 获取伪身份证
        res = requests.request("POST", url, headers=self.header, data=payload, verify=False)
        id_card = res.json()['msg']  # 伪身份号
        print(id_card)
        return id_card
    '''
    获取上传图片的地址，新增接口的上传照片功能
    '''
    def reqImageAddress(self):
        url = self.host+"/api/uploadFile"
        payload = {
            'path': '21/memberPhotos/',
            'ifDetectorFlag': 'false',
            'memberId': '0'
        }
        header = {
            'Authorization': 'Bearer ' + self.token
        }
        files = [
            ('files', ('user.png', open('user.png', 'rb'), 'image/png'))
        ]
        res = requests.request("POST", url, headers=header, data=payload, files=files, verify=False)
        image_address = res.json()['msg']  # 获取上传的图片的地址
        print(image_address)
        return image_address
    '''
    新建用户的接口
    falg：1表示新增工头，0表示普通员工
    '''
    def createNewUser(self,flag):
        image_address = self.reqImageAddress()  # 获取上传的图片地址
        #values, l = readExcel().readexcel(path, sheetName)
        url = self.host+"/api/peopleManage/member/add"  # 新增人员
        #for value in values:
        id_card = self.reqIdCard()  # 获取伪身份证
        print(id_card)
        isoverseer = str(value[6])  # 是否为工头 1是工头  0 不是工头
        payload={}
        print(isoverseer)
        print(type(isoverseer))

        if flag == 1 and isoverseer=='1':  #如果相等 那就执行
            print("222222")
            isoverseer = str(value[6])  # 是否为工头 1是工头  0 不是工头
            username = value[0]  # 名字
            phone = str(value[1])
            # worksiteid = value[2]  # 工地id
            typeworkid = value[3]  # 工种
            subid = value[5]  # 分包商
            payload = {
                "memberId": id_card,
                "memberName": username,
                "subcontractorId": subid,
                "subcontractorName": None,
                "overseerId": "",  # 属于哪个工头下
                "overseerName": None,
                "typeOfWorkId": typeworkid,
                "typeOfWorkName": None,
                "phone": phone,
                "sex": None,
                "sexName": None,
                "birthday": None,
                "photo": image_address,
                "memo": None,
                "overseerFlag": isoverseer,
                "isBlack": None,
                "worksiteId": None,
                "helmet": None,
                "worksiteIdPut": self.worksiteId,
                "worksiteIdList": [{"id": self.worksiteId, "name": None}],
                "ifDetectorFlag": False,
                "emergencyPhone": None,
                "emergencyContact": None,
                "papersFrontView": None,
                "papersBackView": None,
                "papersUsefulStartDate": None,
                "papersUsefulEndDate": None,
                "ifPapersUsefulDateUnlimited": 1
            }
            payload = json.dumps(payload)
            res = requests.request('POST', url, headers=self.header, data=payload, verify=False)
            print(res.text)
        elif  flag==0 and isoverseer=='0':
            print('111111')
            isoverseer = str(value[6])  # 是否为工头 1是工头  0 不是工头
            username = value[0]  # 名字
            phone = str(value[1])
            # worksiteid = value[2]  # 工地id
            typeworkid = value[3]  # 工种
            subid = value[5]  # 分包商
            overseerPhone = str(int(value[8]))  # 普通员工用到的工头手机号
            print(overseerPhone)
            overseerid = self.getOverseerId(overseerPhone) #获取该用户对应的工头id
            ids = self.reqOverseerDevices(overseerid,self.worksiteId) #获取该工头下所有安全帽id
            if len(ids) > 0:
                id = ids[0]
            else:
                id = None
            print(id_card)
            payload = {
                "memberId": id_card,
                "memberName": username,
                "subcontractorId": subid,
                "subcontractorName": None,
                "overseerId": overseerid,  # 属于哪个工头下
                "overseerName": None,
                "typeOfWorkId": typeworkid,
                "typeOfWorkName": None,
                "phone": phone,
                "sex": None,
                "sexName": None,
                "birthday": None,
                "photo": image_address,
                "memo": None,
                "overseerFlag": isoverseer,
                "isBlack": None,
                "worksiteId": None,
                "helmet": id,
                "worksiteIdPut": self.worksiteId,
                "worksiteIdList": [{"id": self.worksiteId, "name": None}],
                "ifDetectorFlag": False,
                "emergencyPhone": None,
                "emergencyContact": None,
                "papersFrontView": None,
                "papersBackView": None,
                "papersUsefulStartDate": None,
                "papersUsefulEndDate": None,
                "ifPapersUsefulDateUnlimited": 1
            }
            payload = json.dumps(payload)
            res = requests.request('POST', url, headers=self.header, data=payload, verify=False)
            print(res.text)





    '''
    通过手机号查找用户的id   
    '''
    def getOverseerId(self,phoneNum):
        url = self.host+"/api/peopleManage/member/list?pageNum=1&pageSize=10&phone={}&orderByColumn=update_time&isAsc=desc".format(phoneNum)
        payload = {}
        print(url)
        res = requests.request('POST', url, headers=self.header,data=payload,verify=False)
        id = res.json()['rows'][0]['memberId']
        return id


    '''
    给对应工头分配安全帽
    '''
    def shareDevice(self,deviceIds,overseerId):
        url = self.host+"/api/helemetManager/distribution/distributedUpdate"
        payload = {
            "worksiteId":self.worksiteId,
            "overseerId":overseerId,
            "cancelDistributionList":[],
            "additionalDistributionList":deviceIds,
            "signList":[]
        }
        payload = json.dumps(payload)
        res = requests.request('POST', url, headers=self.header,data=payload, verify=False)
        print(res.text)

    '''
    签收安全帽
    '''
    def signDevices(self,deviceIds,overseerId):
        url = self.host+"/api/helemetManager/distribution/distributedUpdate"
        payload = {
            "worksiteId": self.worksiteId,
            "overseerId": overseerId,
            "cancelDistributionList": [],
            "additionalDistributionList": [],
            "signList": deviceIds
        }
        payload = json.dumps(payload)
        res = requests.request('POST', url, headers=self.header, data=payload, verify=False)
        print(res.text)

    """
    获取该工头下的安全帽
    """
    def reqOverseerDevices(self,overseerId,worksiteId):
        url = self.host+"/api/deviceManage/device/noOwnerTagListByOverseerId?worksiteId={}&overseerId={}".format(worksiteId, overseerId)
        print(url)
        payload = {}
        res = requests.request('POST', url, headers=self.header,data=payload, verify=False)
        l = len(res.json()[0]['options'])
        options = res.json()[0]['options']
        ids=[]
        for i in range(l-1):
            id = options[i]['deviceId']
            ids.append(id)
        print(overseerId+'该工头有'+str(l)+'个安全帽，分别是'+",".join(ids))
        return ids


if __name__ == '__main__':
    host = "https://192.168.3.82:8097"
    token = "eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6ImI1MTNiOWUwLTI2YTMtNDVmMC1hMTI5LTJmN2U3YmE2NWRkNyJ9.9kWvH6x3n8X1XhB0S3ZF3dBq_jt_lsLnf9Zq7fBOECTx5ClBuJSJY0ftvpwKUuUsjXlRtAeTrHfTINEjmqSTVA"
    path = './config/data.xls'
    sheetName = 'user'
    worksiteid =21 #需不需要excel取还是直接给

    ob = CreateUser(token,host,worksiteid)
    values, l = readExcel().readexcel(path, sheetName)
    for value in values:
        #if value[6]==1:   #如果这个值是1 那表示工头
        ob.createNewUser(1)
        ovsphone = value[1]  # 获取工头的phone
        print(ovsphone)
        ovsid = ob.getOverseerId(ovsphone)  # 获取工头的身份证
        ids = value[7].split(',')
        print(ids)
        ob.shareDevice(ids, ovsid)  # 分配安全帽
        ob.signDevices(ids, ovsid)  # 签收安全帽

    for value in values:
        ob.createNewUser(0)  #创建用户 普通用户








